package sd.czw.com.mmgapp.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.yanzhenjie.recyclerview.swipe.Closeable;
import com.yanzhenjie.recyclerview.swipe.OnSwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import sd.czw.com.mmgapp.Contants;
import sd.czw.com.mmgapp.R;
import sd.czw.com.mmgapp.adapter.ShoucangAdapter;
import sd.czw.com.mmgapp.customviews.ListViewDecoration;
import sd.czw.com.mmgapp.model.loginandsign.LoginNormalCallback;
import sd.czw.com.mmgapp.model.loginandsign.LoginNormalModel;
import sd.czw.com.mmgapp.model.personalbean.ShoucangCallback;
import sd.czw.com.mmgapp.model.personalbean.ShoucangModel;
import sd.czw.com.mmgapp.utils.SpUtils;

/**
 * Created by czw
 * desc 描述：
 * on 2017/7/18.
 */
public class ShouCangActivity extends AppCompatActivity {

    @Bind(R.id.smrv)
    SwipeMenuRecyclerView mMenuRecyclerView;
    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.tv_ts)
    TextView tvTs;
    @Bind(R.id.tv_empty)
    TextView tvEmpty;
    private String token;
    private String username;
    private List<ShoucangModel.ErrmsgBean> mdatas = new ArrayList<>();
    private ShoucangAdapter shoucangAdapter;
    private int page = 1;
    private int start = 0;
    private int limit = 6;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shoucang);
        ButterKnife.bind(this);
        token = SpUtils.setToken(this).getString("token", "");
        username = SpUtils.setUsername(this).getString("username", "");
        getdatas(start);
        mMenuRecyclerView.setLayoutManager(new LinearLayoutManager(this));// 布局管理器。
        mMenuRecyclerView.addItemDecoration(new ListViewDecoration());// 添加分割线。
        mMenuRecyclerView.setHasFixedSize(true);
        mMenuRecyclerView.setNestedScrollingEnabled(false);
        // 为SwipeRecyclerView的Item创建菜单就两句话，不错就是这么简单：
        // 设置菜单创建器。
        mMenuRecyclerView.setSwipeMenuCreator(swipeMenuCreator);
        // 设置菜单Item点击监听。
        mMenuRecyclerView.setSwipeMenuItemClickListener(menuItemClickListener);
        shoucangAdapter = new ShoucangAdapter(this, mdatas);
        //menuAdapter.setOnItemClickListener(onItemClickListener);
        mMenuRecyclerView.addOnScrollListener(mOnScrollListener);
        mMenuRecyclerView.setAdapter(shoucangAdapter);
    }

    @OnClick({R.id.rl_back})
    void viewclick(){
        onBackPressed();
    }
    private void getdatas(int start) {
        OkHttpUtils.post().url(Contants.TG_URL).addParams("username", username)
                .addParams("token", token)
                .addParams("time", Contants.Time)
                .addParams("sign", Contants.Sign)
                .addParams("act", "async_collection_list")
                .addParams("start", String.valueOf(start))
                .addParams("limit", String.valueOf(limit))
                .build().execute(new ShoucangCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(ShoucangModel response, int id) {
                if (response.getErrcode() == 1) {
                    List<ShoucangModel.ErrmsgBean> errmsg = response.getErrmsg();
                    mdatas.addAll(errmsg);
                    shoucangAdapter.notifyDataSetChanged();
                    if (mdatas.size() == 0) {
                        tvEmpty.setVisibility(View.VISIBLE);
                        tvTs.setVisibility(View.GONE);
                    } else {
                        tvEmpty.setVisibility(View.GONE);
                        tvTs.setVisibility(View.VISIBLE);
                    }
                }
            }
        });
    }

    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = getResources().getDimensionPixelSize(R.dimen.y150);
            // MATCH_PARENT 自适应高度，保持和内容一样高；也可以指定菜单具体高度，也可以用WRAP_CONTENT。
            int height = ViewGroup.LayoutParams.MATCH_PARENT;

            // 添加右侧的删除按钮
            {
                SwipeMenuItem addItem = new SwipeMenuItem(ShouCangActivity.this)
                        .setBackgroundDrawable(R.drawable.selector_red)// 点击的背景。
                        .setText("删除")
                        .setTextColor(ContextCompat.getColor(ShouCangActivity.this,R.color.white))
                        .setTextSize(16)
                        .setWidth(width) // 宽度。
                        .setHeight(height); // 高度。
                swipeRightMenu.addMenuItem(addItem); // 添加一个按钮到左侧菜单。
            }
        }
    };

    /**
     * 菜单点击监听。
     */
    private OnSwipeMenuItemClickListener menuItemClickListener = new OnSwipeMenuItemClickListener() {
        /**
         * Item的菜单被点击的时候调用。
         * @param closeable       closeable. 用来关闭菜单。
         * @param adapterPosition adapterPosition. item在Adapter中position。
         * @param menuPosition    menuPosition. 菜单的position。
         * @param direction       如果是左侧菜单，值是：{@link SwipeMenuRecyclerView#LEFT_DIRECTION}，
         *                        如果是右侧菜单，值是：{@link SwipeMenuRecyclerView#RIGHT_DIRECTION}.
         */
        @Override
        public void onItemClick(Closeable closeable, final int adapterPosition, int menuPosition, int direction) {
            closeable.smoothCloseMenu();// 关闭被点击的菜单。
            if (direction == SwipeMenuRecyclerView.RIGHT_DIRECTION) {
                OkHttpUtils.post().url(Contants.TG_URL).addParams("username", username)
                        .addParams("token", token).addParams("time", Contants.Time)
                        .addParams("sign", Contants.Sign).addParams("act", "delete_collection")
                        .addParams("rec_id", mdatas.get(adapterPosition).getRec_id()).build()
                        .execute(new LoginNormalCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {

                            }

                            @Override
                            public void onResponse(LoginNormalModel response, int id) {
                                if (response.getErrcode() == 1) {
                                    mdatas.remove(adapterPosition);
                                    shoucangAdapter.notifyItemRemoved(adapterPosition);
                                } else {
                                    Toast.makeText(ShouCangActivity.this, "" + response.getErrmsg(), Toast.LENGTH_SHORT).show();
                                }

                                if (mdatas.size() == 0) {
                                    tvEmpty.setVisibility(View.VISIBLE);
                                    tvTs.setVisibility(View.GONE);
                                } else {
                                    tvEmpty.setVisibility(View.GONE);
                                    tvTs.setVisibility(View.VISIBLE);
                                }
                            }
                        });
            }
        }
    };

    /**
     * 加载更多
     */
    private RecyclerView.OnScrollListener mOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            if (!recyclerView.canScrollVertically(1)) {// 手指不能向上滑动了
                // TODO 这里有个注意的地方，如果你刚进来时没有数据，但是设置了适配器，这个时候就会触发加载更多，需要开发者判断下是否有数据，如果有数据才去加载更多。
                page++;
                start = page * limit;
                getdatas(start);
                shoucangAdapter.notifyDataSetChanged();
            }
        }
    };
}
